import axios from 'axios';
import type { AxiosResponse, AxiosError } from 'axios';
import { useUserIdStore } from '@/stores/UserId';

// 服务端口配置
const SERVICE_PORTS = {
  // 本地开发环境端口配置
  local: {
    user: 9005,
    shop: 9004,
    goods: 9001,
    order: 9002,
    pack: 9003
  },
  // 远程服务器端口配置（部署时使用）
  remote: {
    user: 9005,
    shop: 9004, // 远程可能统一端口
    goods: 9001,
    order: 9002,
    pack: 9003
  }
};

// 当前环境配置
const CURRENT_ENV = 'local'; // 开发时使用 'local'，部署时改为 'remote'
const BASE_HOST = CURRENT_ENV === 'local' ? 'localhost' : '82.157.31.31';

// 创建不同服务的axios实例
const createServiceHttp = (serviceName: keyof typeof SERVICE_PORTS.local) => {
  const port = SERVICE_PORTS[CURRENT_ENV][serviceName];
  
  const instance = axios.create({
    baseURL: `http://${BASE_HOST}:${port}`,
    timeout: 10000,
    headers: { 
      'Content-Type': 'application/json'
    }
  });

  // 请求拦截器
  instance.interceptors.request.use(
    (config) => {
      const userStore = useUserIdStore();
      if (userStore.currentUserId) {
        config.headers['User-Id'] = userStore.currentUserId;
      }
      
      console.log(`🚀 发送${serviceName}请求:`, config.method?.toUpperCase(), config.url);
      return config;
    },
    (error: AxiosError) => {
      console.error(`❌ ${serviceName}请求错误:`, error);
      return Promise.reject(error);
    }
  );

  // 响应拦截器
  instance.interceptors.response.use(
    (response: AxiosResponse) => {
      console.log(`✅ ${serviceName}响应成功:`, response.status, response.config.url);
      return response;
    },
    (error: AxiosError) => {
      console.error(`❌ ${serviceName}响应错误:`, error.response?.status, error.config?.url);
      
      // 统一错误处理
      let errorMessage = '网络请求失败';
      
      if (error.response) {
        switch (error.response.status) {
          case 400:
            errorMessage = '请求参数错误';
            break;
          case 401:
            errorMessage = '未授权，请重新登录';
            break;
          case 403:
            errorMessage = '拒绝访问';
            break;
          case 404:
            errorMessage = '请求的资源不存在';
            break;
          case 500:
            errorMessage = '服务器内部错误';
            break;
          default:
            errorMessage = `请求失败 (${error.response.status})`;
        }
      } else if (error.request) {
        errorMessage = '网络连接失败，请检查网络';
      }
      
      console.error(`${serviceName}错误详情:`, errorMessage);
      
      return Promise.reject({
        ...error,
        message: errorMessage
      });
    }
  );

  return instance;
};

// 导出各服务的HTTP实例
export const userHttp = createServiceHttp('user');
export const shopHttp = createServiceHttp('shop');
export const goodsHttp = createServiceHttp('goods');
export const orderHttp = createServiceHttp('order');
export const packHttp = createServiceHttp('pack');

// 默认导出用户服务实例（向后兼容）
export const http = userHttp;

// 统一响应数据格式
export interface ApiResponse<T = any> {
  code?: number;
  message?: string;
  data: T;
  success?: boolean;
}

export default http; 